<!DOCTYPE html>
<html>
<head>
<title>IIVGRPG Map Editor</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
    td img {
        display: block;
    }
    #saveArea {
        width: 60%
    }
</style>
</head>
<body>

<script type="text/javascript">
var brush = "grass",    // Текущая кисть.
    map = {},           // Карта.
    cellTypes = {       // Типы клеток карты.
        grass: { id:0, name:"grass", src:"grass.png", acc:1 },
        grass2: { id:1, name:"grass2", src:"grass2.png", acc:1 },
        tree: { id:2, name:"tree", src:"tree.png", acc:0 }
    },
    spriteMap,
    accessMap,
    eventMap,
    objects = new Array()

var GROUNDS = {
    0:{src:"grass.png",acc:1}
}

var MAPOBJECTS = {
    0: {
        tiles: [[{src:"flower.png",acc:1}]]
    },
    1: {
        tiles: [[{src:"tree.png",acc:0}]]
    },
    2: {
        tiles: [
            [null,{src:"pyramid4.png",acc:0},null],
            [{src:"pyramid1.png",acc:0},{src:"pyramid2.png",acc:2},{src:"pyramid3.png",acc:0}]
        ]
    }
}

function selectBrush(elem) {
    console.log("Select brush " + elem.value)
    brush = elem.value
}
function paint(elem, i, j) {
    console.log("Paint " + brush + " in [" + i + ", " + j + "]")
    elem.innerHTML = "<img src=\"" + cellTypes[brush].src + "\">"
    map[i][j] = cellTypes[brush]
}
function save() {
    var tmp = new Array()

    for (var i = 0; i < objects.length; i++) {
        tmp.push({x:objects[i][2],y:objects[i][1],type:objects[i][0],objid:objects[i][3]})
    }

    console.log("Save map")
    document.getElementById("saveArea").value = JSON.stringify(tmp)
}
function loadMap() {}
function randomMap(w, h) {
    console.log("Generate objects.")
    var i, j, id = 1

    for (i = 0; i < h; i++) {
        for (j = 0; j < w; j++) {
            if (Math.floor(1 + Math.random() * 20) == 20) {
                objects.push([0, i, j, id++])
            }
        }
    }

    for (i = 0; i < h; i++) {
        for (j = 0; j < w; j++) {
            if (Math.floor(1 + Math.random() * 50) == 50) {
                if (!isMapObjectExists(i, j)) {
                    objects.push([1, i, j, id++])
                }
            }
        }
    }

    for (i = 0; i < h - 1; i++) {
        for (j = 0; j < w - 2; j++) {
            if (Math.floor(1 + Math.random() * 1000) == 1000) {
                if (!isMapObjectExists(i, j)) {
                    objects.push([2, i, j, id++])
                }
            }
        }
    }

    newMap(w, h)
    createMapTable(w, h)
}
function newMap(w, h) {
    console.log("Create new spriteMap, accessMap, eventMap. " + w + "x" + h)

    spriteMap = new Array(h)
    accessMap = new Array(h)
    eventMap = new Array(h)
    var i, j, k, img

    for (i = 0; i < h; i++) {
        spriteMap[i] = new Array(w)
        accessMap[i] = new Array(w)
        eventMap[i] = new Array(w)
        for (j = 0; j < w; j++) {
            spriteMap[i][j] = {ground: document.createElement('img'),
                               objs: new Array()}
            spriteMap[i][j].ground.border = 0
            spriteMap[i][j].ground.src = GROUNDS[0].src
            accessMap[i][j] = parseInt(GROUNDS[0].acc)
        }
    }

    for (k in objects) {
        //console.log("Map object id = " + objects[k][0])
        for (i in MAPOBJECTS[objects[k][0]].tiles) {
            i = parseInt(i)
            for (j in MAPOBJECTS[objects[k][0]].tiles[i]) {
                j = parseInt(j)
                if (MAPOBJECTS[objects[k][0]].tiles[i][j] != null) {
                    //console.log("Add object tile", MAPOBJECTS[objects[k][0]].tiles[i][j].src, "in", (objects[k][2] + j), (objects[k][1] + i))
                    img = document.createElement('img')
                    img.border = 0
                    img.src = MAPOBJECTS[objects[k][0]].tiles[i][j].src
                    spriteMap[objects[k][1] + i][objects[k][2] + j].objs.push(img)
                    accessMap[objects[k][1] + i][objects[k][2] + j] = parseInt(MAPOBJECTS[objects[k][0]].tiles[i][j].acc)
                    if (MAPOBJECTS[objects[k][0]].tiles[i][j].acc == 2) {
                        var id = objects[k][3]
                        eventMap[objects[k][1] + i][objects[k][2] + j] = function() { return function(id) { console.log("Entering", id) }(id) }
                    }
                } else {
                    //console.log("No object tile in", (objects[k][2] + j), (objects[k][1] + i))
                }
            }
        }
    }
    //console.log("Access map", accessMap)
    //console.log("Event map", eventMap)
    for (i in eventMap) {
        for (j in eventMap[i]) {
            if (eventMap[i][j] != undefined) {
                //eventMap[i][j]()
            }
        }
    }
}
function createMapTable(w, h) {
    var body, table, tr, td, img;
    if ( (table = document.getElementById("mapTable")) != null) {
        document.removeChild(table);
    }
    table = document.createElement('table');
    table.id = "mapTable";
    table.border = 1;

    for (var i = 0; i < h; i++) {
        tr = document.createElement('tr');
        for (var j = 0; j < w; j++) {
            td = document.createElement('td');
            td.addEventListener(
                "click",
                (function(i, j) {return function() {paint(this, i, j)}})(i, j),
                false
            );

            if (spriteMap[i][j].objs.length == 0) {
                img = spriteMap[i][j].ground
            } else {
                img = spriteMap[i][j].objs[spriteMap[i][j].objs.length - 1]
            }

            td.appendChild(img);
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }

    body = document.getElementsByTagName('body')[0];
    body.appendChild(table);
}
function isMapObjectExists(i, j) {
    for (var _i in objects) {
        if (objects[_i][1] == i && objects[_i][2] == j) {
            return true
        }
    }

    return false
}
</script>

<!-- Выбор кисти. -->
<input type="radio"
       name="brushes"
       value="grass"
       onclick="selectBrush(this);" checked> <img src="grass.png"> Grass1<br>
<input type="radio"
       name="brushes"
       value="grass2"
       onclick="selectBrush(this);"> <img src="grass2.png"> Grass2<br>
<input type="radio"
       name="brushes"
       value="tree"
       onclick="selectBrush(this);"> <img src="tree.png"> Tree<br>
<br>

<!-- Сохранение результата. -->
<input type="button"
       value="Save"
       onclick="save();return false;">
<hr>

<!-- Карта. -->
<script type="text/javascript">
randomMap(100, 100)
</script>
<hr>

<!-- Область сохранения. -->
<textarea id="saveArea"></textarea>
</body>
</html>
